<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 17/2/22
 * Time: 20:22
 */
namespace Portal\Controller;
use Common\Controller\HomebaseController;
use Think\Verify;

class HackerController extends HomebaseController{

    // 默认注册页
    public function zc(){
        $this->display();
    }

    // 注册
    public function register(){
        if(IS_POST){
            if(M('users')->create() !== false){
                if(M('users')->add($_POST) !== false){
                    exit(json_encode(array("status"=>true, "message"=>"注册成功")));
                }else{
                    exit(json_encode(array("status"=>false, "message"=>"注册失败")));
                }
            }else{
                $this->error(M('users')->getError());
            }
        }
    }

    // 获取某系列下所有课程
    public function xtxx(){
        $id = I("id");
        $where["series_id"] = $id;
        $count = M("course")->where($where)->count();
        $page = $this->page($count, 20);
        $courses = M("course")->where($where)->order('create_at asc')
            ->limit($page->firstRow, $page->listRows)->select();
        $this->assign("courses", $courses);
        $this->assign("page", $page->show());
        // 获取该系列课程的详细
        $courseSeries = M("course_series")->alias("cs")
            ->join("left join hs_lecture as l on cs.lecture_id=l.lecture_id")
            ->find();
        $this->assign("courseSeries", $courseSeries);
        $this->display();
    }

    // 登录页
    public function dl(){
        $this->display();
    }

    // 登录
    public function login(){
        $email = I("user_email");
        $where["user_email"] = $email;
        $where["user_pass"] = I("psw");
        $where["user_type"] = I("user_type");
        $info = M("users")->where($where)->find();
        if(!empty($info)){
            // 保存登录信息
            $data['user_login'] = $email;
            $data['user_nicename'] = $email;
            $data['last_login_ip'] = get_client_ip();
            $data['last_login_time'] = date('y-m-d h:i:s',time());
            $result = M("users")->where($where)->save($data);
            if($result){
                $_SESSION['_user'] = array(
                    'user_id' => $info['id'],
                    'user_name' => $info['name']
                );
                exit(json_encode(array("status"=>true, "message"=>"登录成功")));
            }else{
                exit(json_encode(array("status"=>true, "message"=>"登录异常")));
            }
        }else{
            exit(json_encode(array("status"=>false, "message"=>"登录失败")));
        }
    }

    // 退出登录
    public function logout(){
        session('_user', null);
        exit(json_encode(array("status"=>true, "message"=>"退出成功")));
    }

    // 忘记密码页
    public function wjmm(){
        $this->display();
    }

    // 生成验证码
    public function verify(){
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useNoise' => false,
        );
        $verify = new Verify($config);
        $verify->entry();
    }

    // 文章模板
    public function xxy(){
        $id = I('id');
        $info = M('posts')->where("id=$id")->find();
        $this->assign('info', $info);
        $this->display();
    }

    public function check_verify($code, $id = ''){
        $verify = new Verify();
        $res = $verify->check($code, $id);
        if($res){
            exit(json_encode(array("status"=>true, "message"=>"")));
        }else{
            exit(json_encode(array("status"=>false, "message"=>"")));
        }
    }

    // 发送邮件
    public function sendEmail(){
        //exit(json_encode(array("status"=>true, "message"=>"发送成功")));
        $email = I('email');
        // 如果时间间隔不足5分钟,则不允许发
        $send_time = M('users')->where("user_email='$email' and user_type=2")->getField('send_time');
        if(!empty($send_time)){
            $differ = time()-strtotime($send_time);
            if($differ > 300){
                exit(json_encode(array("status"=>false, "message"=>"不能连续发送邮件,5分钟后再试")));
            }
        }
        header("content-type:text/html;charset=utf-8");
        ini_set("magic_quotes_runtime",0);
        try {
            $mail = new \PHPMailer(true);
            $mail->IsSMTP();
            $mail->CharSet='UTF-8'; //设置邮件的字符编码，这很重要，不然中文乱码
            $mail->SMTPAuth   = true;                  //开启认证
            $mail->Port       = 25;
            $mail->Host       = "smtp.163.com";
            $mail->Username   = "fenaadou@163.com";
            $mail->Password   = "18912384746";
            //$mail->IsSendmail(); //如果没有sendmail组件就注释掉，否则出现“Could  not execute: /var/qmail/bin/sendmail ”的错误提示
            $mail->AddReplyTo("fenaadou@163.com","mckee");//回复地址
            $mail->From       = "fenaadou@163.com";
            $mail->FromName   = "创客空间";
            $to = $email;
            $mail->AddAddress($to);
            $mail->Subject  = "创客空间找回密码邮件";
            $randomStr = $this->random();
            $time = date('y-m-d H:i:s',time());
            $data['email_yzm'] = $randomStr;
            $data['send_time'] = $time;
            // 将用户验证码及发送时间储存
            $result = M('users')->where("user_email='$email' and user_type=2")->save($data);
            if($result === false){
                exit(json_encode(array("status"=>true, "message"=>"发送失败")));
            }
            $mail->Body = "<center>
                            <h5>您好,&nbsp;$email</h5><h5>您的验证码是:&nbsp;<font color='#ff8c00'>$randomStr</font></h5>
                            <h5>该验证邮件有效期为30分钟,超时请重新发送邮件</h5><br/>
                            <h5>发件时间: $time</h5>
                            <h5>此邮件为系统自动发出的,请勿直接回复</h5>
                            </center>
                          ";
            $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; //当邮件不支持html时备用显示，可以省略
            $mail->WordWrap   = 80; // 设置每行字符串的长度
            //$mail->AddAttachment("f:/test.png");  //可以添加附件
            $mail->IsHTML(true);
            $mail->Send();
            exit(json_encode(array("status"=>true, "message"=>"发送成功")));
        } catch (phpmailerException $e) {
            exit(json_encode(array("status"=>true, "message"=>"发送失败")));
        }
    }

    // 邮件返回页
    public function yjfs(){
        $email = I('email');
        $this->assign('email', $email);
        $this->display();
    }

    // 重置密码页面
    public function czmm(){
        $email = I('email');
        $this->assign('email', $email);
        $this->display();
    }

    // 重置密码
    public function changePsw(){

        $email = I('email');
        $code = I('code');
        $psw = I('psw');
        $info = M('users')->where("user_email='$email' and user_type=2")->field('send_time,email_yzm')->find();
        if($code != $info['email_yzm']){
            exit(json_encode(array("status"=>false, "message"=>"验证码不正确")));
        }
        $differ = time()-strtotime($info['send_time']);
        if($differ > 1800){
            exit(json_encode(array("status"=>false, "message"=>"验证码已超时")));
        }else{
            $data['user_pass'] = $psw;
            $result = M('users')->where("user_email='$email' and user_type=2")->save($data);
            if($result !== false){
                exit(json_encode(array("status"=>true, "message"=>"重置成功")));
            }else{
                exit(json_encode(array("status"=>false, "message"=>"重置密码异常")));
            }
        }
    }

    // 生成随机字符串
    function random($length=6, $type='string', $convert=0){
        $config = array(
            'number'=>'1234567890',
            'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

        if(!isset($config[$type])) $type = 'string';
        $string = $config[$type];

        $code = '';
        $strlen = strlen($string) -1;
        for($i = 0; $i < $length; $i++){
            $code .= $string{mt_rand(0, $strlen)};
        }
        if(!empty($convert)){
            $code = ($convert > 0)? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

}